<template>
  <div class="projectType-container">
    <section class="top">
      <div class="title">
        <PmBreadcrumb />
        <span style="font-weight: 400; font-size: 18px; line-height: 22px"
          >项目类型</span
        >
        <el-icon size="10" style="margin: 0 6px"><ArrowRight /></el-icon>
        <span>{{ route.query.pmType }}</span>
      </div>
      <div style="display: flex; gap: 12px"></div>
    </section>
    <div class="tabsContainer">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane
          label="生命周期/审批"
          name="lifecycleOrAudio"
        ></el-tab-pane>
        <el-tab-pane
          label="项目自定义字段"
          name="projectCustomFields"
        ></el-tab-pane>
      </el-tabs>
      <div v-show="activeName === 'lifecycleOrAudio'" class="selectContainer">
        <el-button
          v-if="
            projectTypeDetail.projectLifecycleId &&
            activeName === 'lifecycleOrAudio'
          "
          @click="handleUnlink"
          style="margin-right: 16px"
          type="text"
          >取消关联</el-button
        >
        <el-select
          v-show="activeName === 'lifecycleOrAudio'"
          v-model="currentLifecycleId"
          style="width: 300px"
          placeholder="请选择生命周期"
          @change="handleLinkLifeCycle"
        >
          <el-option
            v-for="item in lifeCycleList"
            :index="item.id"
            :value="item.id"
            :label="item.name"
            >{{ item.name }}</el-option
          >
        </el-select>
      </div>
      <div
        v-show="activeName === 'projectCustomFields'"
        class="selectContainer"
      >
        <el-button
          v-if="projectTypeDetail.columnDefineTemplateId"
          style="margin-right: 16px"
          @click="handleUnlinkTemplate"
          type="text"
          >取消关联</el-button
        >
        <el-select
          style="width: 300px"
          placeholder="请选择关联的项目自定义字段模版"
          @change="handleLinkTemplate"
          v-model="currentTemplateId"
        >
          <el-option
            v-for="item in templateOptions"
            :index="item.id"
            :value="item.id"
            :label="item.name"
            >{{ item.name }}</el-option
          >
        </el-select>
      </div>
    </div>
    <div class="content">
      <editLifecycle
        :lifecycleId="projectTypeDetail.projectLifecycleId || ''"
        mode="preview"
        v-show="activeName === 'lifecycleOrAudio'"
      />
      <div
        v-if="activeName === 'projectCustomFields'"
        class="wbs-tree-container"
      >
        <!--   表格   -->
        <CLTable
          v-loading="loading"
          :fields="fields"
          :initial-data="fieldsList"
          :line-height="currentLineHeight"
          :tableConfig="tableConfig"
        >
        </CLTable>
        <!-- 字段配置悬浮层 -->
        <FieldConfigPopup
          :fields="currentFields"
          :position="fieldConfigPosition"
          :visible="showFieldConfig"
          @close="showFieldConfig = false"
          @fieldsChange="handleFieldsChange"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { useRoute } from "vue-router";
  import { ArrowRight } from "@element-plus/icons-vue";
  import editLifecycle from "@/views/pm/globalSetting/globalLifecycle/lifecycle/editLifecycle.vue";
  import { onMounted, ref, provide } from "vue";
  import PmBreadcrumb from "@/components/PmBreadcrumb.vue";
  import { listLifeCycle } from "@/api/lifeCycle.ts";
  import type {
    LifeCycleEntity,
    queryPagesType,
  } from "@/interface/lifecycle.ts";
  import {
    detailProjectType,
    updateProjectType,
  } from "@/api/pm/globalProjectTask.ts";
  import type {
    createProjectParamsType,
    projectTypeVo,
  } from "@/interface/pm/globalProjectType.ts";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { getTemplateList } from "@/api/pm/customFieldTemplate.ts";
  import type { ColumnDefinedTemplateEntityRes } from "@/interface/task.ts";
  import CLTable from "@/components/CLTable/index.vue";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import { tableFields } from "./fields/index.ts";
  import type { DynamicField } from "@/data/wbsFields.ts";
  import dist from "@/utils/dist.ts";

  const loading = ref(false);
  const route = useRoute();
  const activeName = ref("lifecycleOrAudio");
  const currentLifecycleId = ref("");
  const currentTemplateId = ref("");
  const fieldsList = ref<ColumnDefinedTemplateEntityRes[]>([]);
  const projectTypeDetail = ref<projectTypeVo>({} as projectTypeVo);

  const lifeCycleList = ref<LifeCycleEntity[]>([]);
  const getLifecycleAll = async () => {
    const params: queryPagesType = {
      pageNo: 1,
      pageSize: 100,
      conditions: [
        { field: "type", operator: "=", value: "PROJECT" },
        { field: "status", operator: "=", value: "NORMAL" },
        { field: "managementVisible", operator: "=", value: "YES" },
      ],
    };
    const res = await listLifeCycle(params);
    lifeCycleList.value = res.result || [];
  };
  const fieldsTypeMap: any = {};
  const getProjectTypeDetail = async () => {
    // console.log("getProjectTypeDetail", route.params);
    const res = await detailProjectType(route.query.id as string);
    projectTypeDetail.value = res;
    currentLifecycleId.value = res.projectLifecycleId || "";
    currentTemplateId.value = res.columnDefineTemplateId || "";
    fieldsList.value = JSON.parse(res?.columnDefined?.config || "[]").map(
      (item: ColumnDefinedTemplateEntityRes) => {
        item.requiredName = item.required ? "必填" : "非必填";
        item.typexName = fieldsTypeMap[item.uiType];
        item.invisibleStatus = item.invisible === 1 ? "是" : "否";
        return item;
      },
    ) as ColumnDefinedTemplateEntityRes[];
    console.log("fieldsList", fieldsList.value, fieldsTypeMap);
  };
  const handleUnlink = () => {
    ElMessageBox.confirm(
      "取消关联会解除该项目类型与生命周期的关联关系，确定取消关联么?",
      "取消关联",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
        draggable: true,
      },
    )
      .then(async () => {
        const params: createProjectParamsType = {
          id: projectTypeDetail.value.id,
          projectLifecycleId: "",
        };
        await updateProjectType(params);
        ElMessage({
          type: "success",
          message: "取消关联成功",
        });
        getProjectTypeDetail();
      })
      .catch(() => {});
  };

  const handleLinkLifeCycle = () => {
    ElMessageBox.confirm(
      "关联该生命周期与该项目类型的关联关系，配置后对后续使用该类型的项目生效，确定关联么？",
      "关联提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
        draggable: true,
      },
    )
      .then(async () => {
        const params: createProjectParamsType = {
          id: projectTypeDetail.value.id,
          projectLifecycleId: currentLifecycleId.value,
        };
        await updateProjectType(params);
        ElMessage({
          type: "success",
          message: "关联成功",
        });
        getProjectTypeDetail();
      })
      .catch(() => {});
  };

  // 项目自定义字段
  const templateOptions = ref<ColumnDefinedTemplateEntityRes[]>([]);
  const getCustomFieldTemp = async () => {
    const params = {
      conditions: [],
      pageNo: 1,
      pageSize: 100,
      targetType: "PROJECT_TYPE",
    };
    const res = await getTemplateList(params);
    templateOptions.value = res.result || [];
  };

  // 表格
  const fields = ref<DynamicField[]>(tableFields); // table表格展示列
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high" | "ultra-high">(
    "low",
  );
  const tableConfig = ref({
    editable: false,
    borderMode: "none",
    tableH: "calc(100vh - 135px)",
    showOperationsColumn: false, // 是否显示操作列
    OperationsColumnMode: "icon", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 10, //自定义操作列宽度
    frozenColCount: 0, // 冻结前面列数
    rightFrozenColCount: 0, // 冻结后面列数
    page: {
      enable: true,
    },
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    // rowSeriesNumber: {
    //   dragOrder: true, // 开启行号拖拽排序
    // },
    // borderMode: "none", // 表格边框模式，none为无边框
  });

  // 配置字段
  const currentFields = ref<DynamicField[]>([]);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const showFieldConfig = ref(false);

  // 处理字段配置变化
  const handleFieldsChange = (updatedFields: DynamicField[]) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };
  // const addRecord = (newRecords: ProjectNode[]) => {
  //   tableData.value = [...newRecords];
  // };
  //
  // // 提供给所有子孙组件使用
  // provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);

  const handleLinkTemplate = async () => {
    ElMessageBox.confirm(
      "关联该生命周期与该项目类型的关联关系，配置后对后续使用该类型的项目生效，确定关联么？",
      "关联提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
        draggable: true,
      },
    )
      .then(async () => {
        const params: createProjectParamsType = {
          id: projectTypeDetail.value.id,
          columnDefineTemplateId: currentTemplateId.value,
        };
        await updateProjectType(params);
        ElMessage({
          type: "success",
          message: "关联成功",
        });
        getProjectTypeDetail();
      })
      .catch(() => {});
  };
  const handleUnlinkTemplate = async () => {
    ElMessageBox.confirm(
      "取消关联会解除该项目类型与项目自定义字段模板的关联关系，确定取消关联么?",
      "取消关联",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
        draggable: true,
      },
    )
      .then(async () => {
        const params: createProjectParamsType = {
          id: projectTypeDetail.value.id,
          columnDefineTemplateId: "",
        };
        await updateProjectType(params);
        ElMessage({
          type: "success",
          message: "取消关联成功",
        });
        getProjectTypeDetail();
      })
      .catch(() => {});
  };
  onMounted(async () => {
    const fieldDist = await dist.getDictData("sdm.global.defined.filedType");
    fieldDist.items.map((item) => {
      fieldsTypeMap[item.code] = item.displayName;
    });
    getCustomFieldTemp();
    await getLifecycleAll();
    getProjectTypeDetail();
  });
</script>

<style scoped lang="scss">
  .projectType-container {
    display: flex;
    flex-direction: column;
    //padding: 16px;
    height: 100%;
    box-sizing: border-box;
  }
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 20px 10px 20px;
    .title {
      font-weight: 500;
      font-size: 18px;
      line-height: 22px;
    }
  }
  .tabsContainer {
    position: relative;
    .selectContainer {
      position: absolute;
      top: 0;
      right: 20px;
    }
    :deep(.el-tabs) {
      padding: 0 20px;
    }
    :deep(.el-tabs__header) {
      margin: 0 !important;
    }
  }
  .content {
    flex: 1;
    .wbs-tree-container {
      background-color: #fff;
      position: relative;
      padding: 16px;
    }
  }
</style>
